package ruide_info_mvc.base.core.exception;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.NoHandlerFoundException;
import ruide_info_mvc.base.core.exception.customException.CommonException;
import ruide_info_mvc.base.core.exception.customException.ManualParamException;
import ruide_info_mvc.base.core.exception.customException.TypeParamsException;
import ruide_info_mvc.base.model.response.BaseResponseBean;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.UndeclaredThrowableException;

/**
 * 统一异常处理
 *
 * @ClassName ExceptionHandle
 * @Author wangBo
 * @Date 2019/7/21 0021 上午 11:20
 * @Version 1.0
 */
@ControllerAdvice(basePackages = {"ruide_info_mvc.base.contoller"})
public class ExceptionHandle implements IExceptionHandle {

    private static Logger logger = LoggerFactory.getLogger(ExceptionHandle.class);

    @ExceptionHandler(value = {Exception.class})
    @ResponseBody
    @Override
    public BaseResponseBean exceptionHandle(Exception e) {
        BaseResponseBean baseResponseBean = null;
        try {
            Throwable throwable = null;
            if (throwable instanceof UndeclaredThrowableException) {
                throwable = throwable.getCause();
            } else {
                throwable = e;
            }
            if (throwable instanceof ManualParamException) {
                return BaseResponseBean.buildError(300, ((ManualParamException) throwable).getErrorMsg());
            } else if (throwable instanceof NoHandlerFoundException) {     // 404
                return BaseResponseBean.buildError(300, new ManualParamException("未找到目标!").getErrorMsg());
            } else if (throwable instanceof TypeParamsException) {
                return BaseResponseBean.buildError(300, ((TypeParamsException) throwable).getErrorMsg());
            } else if (throwable instanceof CommonException) {          // 公共异常
                return BaseResponseBean.buildError(300, ((CommonException) throwable).getErrorMsg());
            } else if (throwable instanceof  InvocationTargetException) {           // 调用目标异常
                return BaseResponseBean.buildError(300, ((CommonException) throwable).getErrorMsg());
            }
        } catch (Exception ex) {
            logger.error("", ex);
            baseResponseBean = BaseResponseBean.buildError(ex.getMessage());
        }
        return baseResponseBean;
    }
}